import router from '@system.router'
import rdb from '@ohos.data.rdb'
import deviceManager from '@ohos.distributedHardware.deviceManager'
import ability_featureAbility from '@ohos.ability.featureAbility'

let rdbStore
let dmInstance = null;
let context = ability_featureAbility.getContext()
const BACKUP_STORE_NAME = "distributed_rdb_bak.db"
var nameList = ["Leila", "Ursa", "Crystal", "Rebecca", "Taylor", "Elizabeth", "Ayn", "Rosa", "Beatrice", "Tracy",
"Emily", "Glenn", "Iris", "Sara", "Freddie", "Cindy", "Devin", "Karen", "Zillah", "Ivy", "Xena", "Aimee", "Olivia",
"Elisabeth", "Ulrica", "Chris", "Leslie", "Felicity", "Alessandra", "Cherie", "Sonia", "Elsa", "Natasha", "Candy",
"Kim", "Darleen", "Lillian", "Abigail", "Del", "Serena", "Candice", "Gemma", "Irene", "Rita", "Genevieve", "Nora",
"Ivory", "Niki", "Jacky", "Betty", "Isabelle", "Ray", "Patty", "Cathy", "Tanya", "Alison", "Rachel", "Julia",
"Julie", "Yasmine", "Susan", "Odin", "Emma", "Jessie", "Zoie", "Paula", "Carrie", "Harriet", "Christian", "Hana",
"Charlotte", "Terry", "Leah", "Ximena", "Frederica", "Wing", "Qara", "Elaine", "Silvia", "Ella", "Francesca",
"Janet", "Phoebe", "Holly", "Xochitl", "Urania", "Qatar", "Yolanda", "Athena", "Georgia", "Beth", "Barbie",
"Della", "Isabella", "Wendi", "Ophelia", "Hanna", "Sarah", "Hayden", "Teresa"];

function random(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

export default {
    data: {
        logText: ""
    },

    onInit() {
        grantPermission();
        //this.title = this.$t('strings.world');
    },

    showLog(info) {
        this.logText += info + "\n"
    },

    onclick: function () {
        router.replace({
            uri: "pages/second/second"
        })
    },


    initDeviceMonitor: function () {
        deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
            if (err) {
                this.showLog("create device manager failed, err=" + err);
                return;
            }
            dmInstance = manager;
            this.showLog("create device manager success");
            dmInstance.on("deviceStateChange", (data) => {
                this.showLog("deviceStateChange: " + JSON.stringify(data));
            });
        });
    },

    createRdbStore: function () {
        let config = {
            name: "distributed_rdb.db"
        }
        let storePromise = rdb.getRdbStore(context,config, 1)
        storePromise.then((store) => {
            rdbStore = store
            this.showLog("open store success")
        }).catch(() => {
            this.showLog("open store failed")
        })
    },

    createTable: function () {
        let sqlStatement = "CREATE TABLE IF NOT EXISTS employee (" +
        "id INTEGER PRIMARY KEY AUTOINCREMENT," +
        "name TEXT NOT NULL," +
        "age INTEGER)";
        let promise1 = rdbStore.executeSql(sqlStatement, null)
        promise1.then(() => {
            this.showLog("create table employee success");
        }).catch(() => {
            this.showLog("create table employee failed")
        })
    },

    setDistributedTables: function() {
        let promise = rdbStore.setDistributedTables(['employee'])
        promise.then(() => {
            this.showLog("set employee to be distributed table success");
        }).catch(() => {
            this.showLog("set employee to be distributed table failed");
        })
    },

    insert: function() {
        if (rdbStore == undefined) {
            this.showLog("create or open rdb store first")
            return
        }
        const record = {
            "name": nameList[Math.floor(Math.random() * nameList.length)],
            "age": random(1, 100),
        }
        let promise = rdbStore.insert("employee", record)
        promise.then((rowId) => {
            this.showLog("insert one record success " + rowId)
        }).catch(() => {
            this.showLog("insert one record failed");
        })
    },

    batchInsert: function () {
        let i = 0;
        while (i < 10) {
            this.insert()
            i++
        }
    },

    delete: function () {
        if (rdbStore == undefined) {
            this.showLog("create or open rdb store first")
            return
        }
        let result = rdbStore.querySql("select id from employee order by random() limit 1")
        result.then((resultSet) => {
            if (resultSet.rowCount == 0) {
                this.showLog("No record")
                return
            }
            resultSet.goToFirstRow();

            let employeeId = resultSet.getLong(0);
            let predicates = new rdb.RdbPredicates("employee")
            predicates.equalTo("id", employeeId);
            let promise = rdbStore.delete(predicates)
            promise.then((rowId) => {
                this.showLog("delete one record success id = " + employeeId)
            }).catch(() => {
                this.showLog("delete one record failed id = " + employeeId)
            })
            resultSet.close();
        }).catch(() => {
            this.showLog("query failed")
        })
    },

    update: function () {
        if (rdbStore == undefined) {
            this.showLog("create or open rdb store first")
            return
        }
        let result = rdbStore.querySql("select id from employee order by random() limit 1")
        result.then((resultSet) => {
            if (resultSet.rowCount == 0) {
                this.showLog("No record")
                return
            }
            resultSet.goToFirstRow();
            let employeeId = resultSet.getLong(0);
            const record = {
                "name": nameList[Math.floor(Math.random() * nameList.length)],
                "age": random(1, 100),
            }
            let predicates = new rdb.RdbPredicates("employee")
            predicates.equalTo("id", employeeId);
            let promise = rdbStore.update(record, predicates)
            promise.then((rowId) => {
                this.showLog("update one record success id = " + employeeId + ", name = " + record.name + ", age = " + record.age)
            }).catch(() => {
                this.showLog("update one record failed id = " + employeeId + ", name = " + record.name + ", age = " + record.age)
            })
            resultSet.close();
        }).catch(() => {
            this.showLog("query failed")
        })
    },

    queryByTableName: function(tableName) {
        let promise = rdbStore.querySql("SELECT * FROM " + tableName)
        promise.then((resultSet) => {
            this.showLog(resultSet.columnNames + " rowCount=" + resultSet.rowCount)
            resultSet.goToFirstRow();
            while (resultSet.isEnded == false) {
                let idx = resultSet.getLong(0);
                let name = resultSet.getString(1);
                let age = resultSet.getLong(2);
                this.showLog(idx + " " + name + " " + age);
                resultSet.goToNextRow();
            }
            resultSet.close();
        }).catch(() => {
            this.showLog("query " + tableName + " failed")
        })
    },

    query: function() {
        this.queryByTableName("employee");
    },

    getRemoteDeviceId: function() {
        if (dmInstance == null) {
            this.showLog("click 注册设备监听 first");
            return "";
        }
        let deviceInfos = dmInstance.getTrustedDeviceListSync();
        if (deviceInfos.length == 0) {
            this.showLog("no remote device");
            return "";
        }
        let deviceId = deviceInfos[0].deviceId;
        return deviceId;
    },

    queryDevice: function() {
        this.showLog("queryDevice enter");
        let deviceId = this.getRemoteDeviceId();
        let promise = rdbStore.obtainDistributedTableName(deviceId, "employee");
        promise .then((tableName) => {
            this.showLog("tableName=" + tableName);
            this.queryByTableName(tableName);
        }) .catch((err) => {
            this.showLog("obtainDistributedTableName failed");
        });
    },

    onDataChange: function(devices) {
        this.showLog("onDataChange: " + devices.length);
        for (let i = 0; i < devices.length; i++) {
            this.showLog(devices[i]);
        }
    },

    subscribe: function() {
        this.showLog("subscribe");
        rdbStore.on("dataChange", rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.onDataChange);
    },

    unsubscribe: function() {
        this.showLog("unsubscribe");
        rdbStore.off("dataChange", rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.onDataChange);
    },

    sync: function() {
        this.showLog("begin sync ...");
        let predicate = new rdb.RdbPredicates("employee");
        predicate.inAllDevices();
        let promise = rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicate);
        promise.then((result) => {
            this.showLog("sync: " + result);
        }).catch((err) => {
            this.showLog("sync failed");
        })
    },

    backup: function () {
        let promiseBackup = rdbStore.backup(BACKUP_STORE_NAME)
        promiseBackup.then(() => {
            this.showLog("database backup success ");
        }).catch((err) => {
            this.showLog("backup database failed " + err);
        })
    },

    restore: function () {
        let promiseRestore = rdbStore.restore(BACKUP_STORE_NAME)
        promiseRestore.then(() => {
            this.showLog("database restore success ");
        }).catch((err) => {
            this.showLog("database restore failed " + err);
        })
    },

    clearData: function () {
        let predicate = new rdb.RdbPredicates("employee");
        let promise = rdbStore.delete(predicate);
        promise.then((number) => {
            this.showLog("remove " + number + " records");
        }).catch((err) => {
            this.showLog("remove records failed");
        })
    },

    clearLog: function () {
        this.logText = ""
    }
}

function grantPermission() {
    console.info('grantPermission');
    let context = ability_featureAbility.getContext();
    context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
        console.info(`result.requestCode=${result.requestCode}`)

    })
    console.info('end grantPermission');
}


